package com.lx.note.service.impl;

import com.lx.common.constant.UserConstant;
import com.lx.common.vo.Message;
import com.lx.note.entity.UserBO;
import com.lx.note.entity.UserLoginDTO;
import com.lx.note.entity.UserRegisterDTO;
import com.lx.note.ex.NameException;
import com.lx.note.ex.PasswordException;
import com.lx.note.ex.UserExistException;
import com.lx.note.mapper.UserMapper;
import com.lx.note.service.itf.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * Created by Administrator on 2018/5/24 0024.
 */
@Service(value = "userService")
public class UserServiceImpl implements UserService{


    @Resource
    private UserMapper userMapper;

    public Message<UserBO> login(UserLoginDTO userLoginDTO) throws NameException,PasswordException{
        String name = userLoginDTO.getName();
        String password = userLoginDTO.getPassword();
        if(StringUtils.isBlank(name)){
            throw new NameException("用户名错误");
        }
        if(StringUtils.isBlank(password)){
            throw new PasswordException("密码错误");
        }
        // 获取用户信息 校验密码
        UserBO userBO = userMapper.getUserBOByName(name);
        if(userBO == null){
            throw new NameException("用户不存在");
        }
        String md5 = DigestUtils.md5Hex(password+UserConstant.SALT_PASSWORD);

        if(StringUtils.equals(md5,userBO.getPassword())){
            return Message.ok("登录成功", userBO);//登录成功
        }
        throw new PasswordException("密码错误");
    }

    @Override
    public Message regist(UserRegisterDTO userRegisterDTO) {
        userRegisterDTO.setId(UUID.randomUUID().toString());
        String name =userRegisterDTO.getName();
        UserBO userBO = userMapper.getUserBOByName(name);
        if(userBO != null) {
            throw new UserExistException(name +" 已经注册");
        }
        if(StringUtils.isBlank(userRegisterDTO.getNick())){
            userRegisterDTO.setNick(name);
        }
        //所有注册参数符合注册规则,保存数据
        String password = userRegisterDTO.getPassword();
        String md5  = DigestUtils.md5Hex(password+UserConstant.SALT_PASSWORD);
        userRegisterDTO.setPassword(md5);
        int result = userMapper.saveRegistUserAndGetId(userRegisterDTO);
        Message message = result > 0 ? Message.ok("注册成功") : Message.fail("注册失败");
        return message;
    }
}
